"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 防篡改
Case Name   : 验证在事务中执行用户的解锁，解锁状态不能回滚
Create At   : 2022-03-10
@zou_jialiang0501080719
Description :
    1.设置参数并重启数据库enableSeparationOfDuty=on
    2.创建并锁定用户
    3.在事务中解锁用户并进行rollback
    4.查看系统表信息
    5.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.解锁未回滚成功，rolstatus为0呈解锁正常状态
    5.成功
History     :
"""


import os
import unittest
from yat.test import macro
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger


class ModifyCase(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.user_name = 'u_security_userlockprivilege_8'
        self.default_value = self.common.show_param('enableSeparationOfDuty')

    def test_security(self):
        text = '-----step1：设置参数并重启数据库enableSeparationOfDuty=on; ' \
               'expect:成功-----'
        self.log.info(text)
        mod_msg = \
            self.primary_sh.execute_gsguc('set',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          'enableSeparationOfDuty=on')
        self.log.info(mod_msg)
        self.assertTrue(mod_msg, '执行失败:' + text)
        restart_msg = self.primary_sh.restart_db_cluster()
        self.log.info(restart_msg)
        status = self.primary_sh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status,
                        '执行失败:' + text)

        text = '-----step2：创建并锁定用户 expect:成功-----'
        self.log.info(text)
        create_cmd = f"drop user if exists {self.user_name} cascade; " \
            f"create user {self.user_name} sysadmin " \
            f"password '{macro.PASSWD_REPLACE}' ; " \
            f"alter user {self.user_name} account lock;"
        msg = self.primary_sh.execut_db_sql(create_cmd)
        self.log.info(msg)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG and
                      self.constant.ALTER_ROLE_SUCCESS_MSG, msg,
                      '执行失败:' + text)

        text = '-----step3：在事务中解锁用户并进行rollback expect:成功-----'
        self.log.info(text)
        create_cmd = f'''start transaction;
                alter user {self.user_name} account unlock;
                rollback;'''
        msg = self.primary_sh.execut_db_sql(create_cmd)
        self.log.info(msg)
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG and
                      self.constant.ALTER_ROLE_SUCCESS_MSG and
                      self.constant.ROLLBACK_MSG, msg, '执行失败:' + text)

        text = '----step4:查看系统表信息 ' \
               'expect:解锁未回滚成功，rolstatus为0呈解锁正常状态----'
        self.log.info(text)
        sql_cmd = self.primary_sh.execut_db_sql(f'''select a.rolname,
                            b.rolstatus from pg_authid a,pg_user_status b 
                            where a.rolname like '%{self.user_name}%' 
                            and a.oid=b.roloid order by rolname;''')
        self.log.info(sql_cmd)
        self.assertTrue(sql_cmd.count('0') == 1, "执行失败:" + text)

    def tearDown(self):
        text = '----step5:清理环境 expect:成功----'
        self.log.info(text)
        self.log.info('删除用户')
        sql_cmd = self.primary_sh.execut_db_sql(
            f"drop user {self.user_name} cascade; ")
        self.log.info(sql_cmd)
        self.log.info('恢复参数默认值')
        mod_msg1 = \
            self.primary_sh.execute_gsguc('set',
                                          self.constant.GSGUC_SUCCESS_MSG,
                                          f'enableSeparationOfDuty='
                                          f'{self.default_value}')
        self.log.info(mod_msg1)
        restart_msg = self.primary_sh.restart_db_cluster()
        self.log.info(restart_msg)
        status = self.primary_sh.get_db_cluster_status()
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, sql_cmd,
                      '执行失败:' + text)
        self.assertTrue("Degraded" in status or "Normal" in status,
                        '执行失败:' + text)
        self.assertTrue(mod_msg1, '执行失败:' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
